package com.fsm.system.serviceImpl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fsm.common.tools.Result.Result;
import com.fsm.common.tools.util.Md5Utils;
import com.fsm.common.verify.AuthService;
import com.fsm.common.verify.VerifyCodeEntity;
import com.fsm.system.entity.TSystemUser;
import com.fsm.system.entity.dto.LoginDto;
import com.fsm.system.entity.table.TSystemUserTable;
import com.fsm.system.mapper.SystemUserMapper;
import com.fsm.system.service.LoginService;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.mybatisflex.core.tenant.TenantManager.ignoreTenantCondition;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthService authService;
    @Autowired
    private SystemUserMapper systemUserMapper;
    /**
     * 系统用户登录接口
     *
     * @param
     * @return
     */
    @Override
    public Result loginIn(LoginDto loginDto) throws Exception {
//        RedisUtil redisUtil = new RedisUtil();
//        Long expireTime = redisUtil.getExpire(loginDto.getVerifyId());
//        if(expireTime == null || expireTime <= 0){
//            return Result.fail("验证码已过期，请重新生成验证码");
//        }
//        String value = (String) redisUtil.get(loginDto.getVerifyId());
//        if(!value.equals(loginDto.getText())){
//            return Result.fail("验证码不正确，请重试");
//        }
        ignoreTenantCondition();
        //查询用户是否存在
        QueryWrapper systemUserQueryWrapper = new QueryWrapper();
        systemUserQueryWrapper.where(TSystemUserTable.T_SYSTEM_USER.LOGIN_NAME.eq(loginDto.getLoginName()));
        TSystemUser TSystemUserOne = systemUserMapper.selectOneWithRelationsByQuery(systemUserQueryWrapper);
        if(ObjectUtil.isEmpty(TSystemUserOne)){
            return Result.fail("当前用户不存在");
        }
        if(TSystemUserOne.equals(Md5Utils.code(loginDto.getPassword()))){
            return Result.fail("密码错误，无法登陆");
        }
        //用户登录
        StpUtil.login(TSystemUserOne.getId());
        //保存用户
        StpUtil.getSession().set("systemUser", TSystemUserOne);
        TSystemUserOne.setPassword("******");
        TSystemUserOne.setToken(StpUtil.getTokenValue());
        //登录成功后，删除该key值
//      redisUtil.del(loginDto.getVerifyId());
        return Result.ok(TSystemUserOne);
    }
    /**
     * 系统用户登录登出
     *
     * @param
     * @return
     */
    @Override
    public Result loginOut() throws Exception {
        // 当前会话注销登录
        StpUtil.logout();
        return Result.ok();
    }
    /**
     * 生成验证码
     *
     * @param
     * @return
     */
    @Override
    public Result createVerify() throws Exception {
        VerifyCodeEntity verifyCodeEntity = authService.generateVerifyCode();
        verifyCodeEntity.setText("");
        return Result.ok(verifyCodeEntity);
    }
}
